package synchronize.synchronize005;

/**
 * synchronized异常
 */
public class SyncException {
    private int i = 0;

    public synchronized void operation() {
        while (true) {
            try {
                i++;
                Thread.sleep(200);
                System.out.println(Thread.currentThread().getName() + ",i = " + i);
                if (i == 10) {
                    //为了抛异常
                    Integer.parseInt("a");
                }

            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(" log info i = " + i);
            }
        }
    }

    /**
     * 这个例子用来验证synchronized运行时出现异常锁自动释放，下一个等待者得到锁继续运行
     * 如果想终止程序抛出异常即可
     * @param args
     */
    public static void main(String[] args) {
        final SyncException se = new SyncException();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                se.operation();
            }
        }, "t1");
        t1.start();
    }


}
